
import { Contract, ethers, providers } from 'ethers'
class ContractUtil {
    public static provider: ethers.providers.Web3Provider;
    public static getProvider = () => {
        if ((window as any).ethereum) {
            if (!ContractUtil.provider) {
                ContractUtil.provider = new ethers.providers.Web3Provider((window as any).ethereum)
            }
        }
        return ContractUtil.provider
    }
    public static getContract = (address: string, abi: any, isReadOnly = false) => {
        let contractInstance: Contract;
        if (isReadOnly) {
            //创建可读合约 
            contractInstance = new ethers.Contract(address, abi, ContractUtil.provider)
        } else {
            //创建可读可写合约
            const signer = ContractUtil.provider.getSigner()
            contractInstance = new ethers.Contract(address, abi, signer)
        }
        return contractInstance
    }
    //通过私钥获取公钥
    public static getAccountAddressByPrivate = (privateKey: string) => {
        const wallet = new ethers.Wallet(privateKey,ContractUtil.getProvider());
        const publicKey = wallet.publicKey;//只是地址的另外一种形势展示而已 
        const address = wallet.address
        return address;
    }
}
export default ContractUtil